package server;

import java.io.IOException;

import communication.Request;
import communication.RequestInputStream;
import communication.ServerConnection;
import communication.SocketConnection;

/**
 * <h1>Class InputListener</h1>
 * 
 * This class represents a thread which is reading at some port in the server
 * and stores requests into the server buffer as fast as possible.
 * 
 * @author Tomas
 * @date March 4 2009
 */
public class InputListener extends Thread {

	/**
	 * Instance of the server.
	 */
	protected ServerMonitor server = null;
	
	/**
	 * Boolean value to indicate if the thread is running. If we want to
	 * turn of the server, we should do it nicely.
	 */
	protected boolean finished;
	
	/**
	 * Connection to a local port in which we are listening for messages.
	 */
	protected static ServerConnection connection = null;
	
	/**
	 * Stream from which we read the requests made by the clients.
	 */
	protected RequestInputStream input = null;
	
	/**
	 * Default constructor. It initializes this thread to listen to some port
	 * and read requests.
	 */
	public InputListener(){
		
		finished = false;
		
		if(connection == null){
			try {
				connection = new ServerConnection(44444);
			} catch (IOException e) {
				LogException.getInstance().logException(e);
			}
		}
		
		
	}
	
	/**
	 * Main loop for the thread. It keeps reading and storing requests.
	 */
	public void run(){

		server = ServerMonitor.getInstance();
		
		while(!finished){
			
			try {
				SocketConnection incomingConnection = null;
				synchronized(connection){
					incomingConnection = connection.accept();
				}
				if(incomingConnection != null){
					//long t0 = System.currentTimeMillis();
					Request req = incomingConnection.readRequest();
					server.storeRequest(req);
					incomingConnection.close();
					//long t1 = System.currentTimeMillis();
					//System.out.println((t1-t0) + " ms");
				}
			} catch (IOException ioe) {
				LogException.getInstance().logException(ioe);
			} catch (ClassNotFoundException cnfe) {
				LogException.getInstance().logException(cnfe);
			}
			
		}
		
	}
	
	/**
	 * Finishes the thread.
	 */
	public void finish(){
		
		finished = true;
		
	}
}
